import 'package:flutter/material.dart';
import 'package:yuan_hang_app/base/full_base_page.dart';
import 'package:yuan_hang_app/res/w_colors.dart';
import 'package:yuan_hang_app/res/w_dimens.dart';
import 'package:yuan_hang_app/utils/common_req_utils.dart';
import 'package:yuan_hang_app/utils/common_utils.dart';
import 'package:yuan_hang_app/utils/size_utils.dart';
import 'package:yuan_hang_app/utils/string_utils.dart';
import 'package:yuan_hang_app/views/home/model/driver_feedback_model.dart';
import 'package:yuan_hang_app/widget/sort_content.dart';
import 'package:yuan_hang_app/widget/status_btn.dart';
import 'package:yuan_hang_app/widget/w_line.dart';
import 'package:yuan_hang_app/widget/w_popup_window.dart';
import 'package:yuan_hang_app/widget/w_text.dart';
import '../../../../base/base_state.dart';
import '../../../../http/api.dart';
import '../../../../http/http_utils.dart';
import '../../../../res/w_constant.dart';
import '../../../../utils/router_helper.dart';
import '../../../../widget/custom_search.dart';
import '../../../../widget/tab_btn.dart';
import '../../../../widget/w_list_view.dart';
import 'drive_feedback_detail_page.dart';
import 'drive_feedback_update_page.dart';

class DriveFeedBackPage extends StatefulWidget {
  final String? phone;
  const DriveFeedBackPage({super.key,this.phone});

  @override
  BaseState<DriveFeedBackPage> createState() => _DriveFeedBackPageState();
}

class _DriveFeedBackPageState extends BaseState<DriveFeedBackPage> {
  int selectedIndex = 0; // 当前选中的标签索引，初始为全部
  List feedBackList = [];
  List<Map> tabList1 = [
    {"value": "0", "title": "全部"},
    {"value": "10041002", "title": "待回访"},
    {"value": "10041001", "title": "已回访"}
  ];
  List<Map> saleManList = WConstant().salesmanList;

  List currentOrderList = [];
  Map sortParams = {};
  String autoPhone = "";


  var mCurrentStatus;

//  int mPage=0;
  //String keyword = "";

  Map<String, dynamic> queryParams = {
    "pageNum": 1,
    "limit": 20,
    "status":"10181003"
  };


  @override
  void initState() {
    if (widget.phone != null) {
      queryParams["queryParam"] = widget.phone;
      autoPhone = widget.phone!;
    }
    super.initState();
  }

  @override
  FullBasePage buildState(BuildContext context) {
    return FullBasePage(
        title: "回访列表",
        child: Column(
          children: <Widget>[
            // 文字标签按钮
            CustomSearch(
              hintText: "客户名称/手机号",
              initText: autoPhone,
              onSortClick: () {
                WPopupWindow.showSort(
                    context: context,
                    sortType: SortType.DRIVE_BACK,
                    sortParams: sortParams,
                    isScrollControlled: false,
                    onSelected: (params) {
                      sortParams = params;
                      print("params$params");
                      params.forEach((key, value) {
                        queryParams[key] = value;
                        if (queryParams.containsKey(key) && value == null) {
                          queryParams.remove(key);
                        }
                      });
                      showLoading();
                      fetchDataList();
                    });
              },
              onTextChange: (text) {
                queryParams["queryParam"] = text;
                queryParams["pageNum"] = 1;
                showLoading();
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            TabBtn(
              tabList: tabList1,
              paddingTop: 5.px,
              paddingBottom: 5.px,
              tabClick: (index) {
                queryParams["pageNum"] = 1;
                queryParams["isProbe"] =
                    index == 0 ? "" : tabList1[index]["value"];
                showLoading();
                CommonUtils.antiShake(fetchDataList);
              },
            ),
            Expanded(
              child: WListView(
                padding: EdgeInsets.zero,
                itemBuilder: _noticeMsgItem,
                getDataList: (currentState, page) {
                  mCurrentStatus = currentState;
                  queryParams["pageNum"] = page;
                  fetchDataList();
                },
              ),
            ),
          ],
        ));
  }

  Widget _noticeMsgItem(context, index, currentOrderList) {
    Map item = currentOrderList[index];
    Map statusInfo = DriverFeedBackModel.exchangeStatus(
        item["isProbe"] == 10041001 ? "已回访" : "待回访");
    return GestureDetector(
        //针对手势点击事件点击对应的项跳转到详情页
        onTap: () => {
              //跳转到详情页，后续替换为id，详情页通过id查询详情信息
              RouteHelper.pushWidget(
                  context, DriveFeedBackDetailPage(feedbackId: item["id"]))
            },
        child: Container(
            alignment: Alignment.center,
            margin: EdgeInsets.only(left: 10.px, right: 10.px, bottom: 10.px),
            padding: EdgeInsets.only(right: 10.px, top: 5.px),
            decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(10.px),
                color: Colors.white,
                boxShadow: const [
                  BoxShadow(
                      //线框阴影线条
                      color: WColors.border,
                      offset: Offset(0, 1),
                      blurRadius: 2)
                ]),
            child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Row(
                    children: [
                      WLine(
                        height: 14.px,
                        width: 4.px,
                        color: WColors.primaryColor,
                        marginRight: 10.px,
                      ),
                      Expanded(
                        child: Row(
                          children: [
                            Flexible(
                              flex: 1,
                              child: WText(
                                StringUtils.safeGetValue(item["customerName"]),
                                overflow: TextOverflow.ellipsis,
                                style: TextStyle(
                                    fontSize: WDimens.tsLarge,
                                    color: WColors.mainTextColor,
                                    fontWeight: FontWeight.bold),
                              ),
                            ),
                            SizedBox(
                              width: 10.px,
                            ),
                          ],
                        ),
                      ),
                      StatusBtn(
                        height: 28.px,
                        width: 60.px,
                        text: item["isProbe"] == 10041001 ? "已回访" : "待回访",
                        isTag: true,
                        isItemBtn: true,
                        color: statusInfo["color"],
                      )
                    ],
                  ),
                  WLine(
                    height: 0.5.px,
                 //   marginBottom: 5.px,
                    marginTop: 5.px,
                    marginLeft: 10.px,
                  ),
                  ItemSingleInfoRow(StringUtils.handleThePhoneStr(item["phone"])),
                  ItemInfoRow(
                      CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.driveType, item["driveType"]),
                      CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.driveMethod, item["driveMethod"])),
                  ItemInfoRow(
                      StringUtils.safeGetValue(CommonReqUtils.exchangeCodeToName(
                          CommonReqUtils.carType, item["modelId"]),placeHolder: "-"),
                      StringUtils.safeGetValue(item["saleMan"],
                          placeHolder: "未知")),
                  Padding(
                    padding: EdgeInsets.only(
                      left: 10.px,
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Offstage(
                          offstage: StringUtils.isEmpty(item["startDriveTime"]),
                          child: Padding(
                            padding: EdgeInsets.only(top: 5.px),
                            child: WText(
                              "开始时间: ${StringUtils.safeGetValue(item["startDriveTime"])}",
                              style: TextStyle(
                                  color: WColors.hintTextColor,
                                  fontSize: WDimens.tsMedium),
                            ),
                          ),
                        ),
                        Offstage(
                          offstage: StringUtils.isEmpty(item["endDriveTime"]),
                          child: Padding(
                            padding: EdgeInsets.only(top: 5.px),
                            child: WText(
                              "结束时间: ${StringUtils.safeGetValue(item["endDriveTime"])}",
                              style: TextStyle(
                                  color: WColors.hintTextColor,
                                  fontSize: WDimens.tsMedium),
                            ),
                          ),
                        ),
                        SizedBox(
                          height: item["isProbe"] != 10041001 ? 0 : 5.px,
                        ),
                        Offstage(
                          offstage: item["isProbe"] != 10041001,
                          child: WText(
                            "回访时间: ${StringUtils.safeGetValue(item["probeTime"])}",
                            style: TextStyle(
                                color: WColors.hintTextColor,
                                fontSize: WDimens.tsMedium),
                          ),
                        ),
                      ],
                    ),
                  ),
                  //只有试驾中或已结束才会有开始时间
                  // ItemInfoRow("开始时间:", "2023-09-12 12:32:12"),
                  WLine(
                    marginTop: 5.px,
                    height: item["isProbe"] != 10041002 ? 0 : 0.5.px,
                    marginLeft: 10.px,
                  ),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.end,
                    children: [
                      Offstage(
                        offstage: item["isProbe"] != 10041002,
                        child: StatusBtn(
                          height: 28.px,
                          width: 68.px,
                          isItemBtn: true,
                          text: "回访",
                          margin: EdgeInsets.symmetric(vertical: 5.px),
                          onPressed: () {
                            RouteHelper.pushWidget(
                                    context,
                                    DriveFeedBackUpdatePage(
                                        feedbackId: item["id"]))
                                .then((isFeedBack) {
                              if (isFeedBack!=null&&isFeedBack) {
                                fetchDataList();
                                setState(() {});
                              }
                            });
                          },
                        ),
                      ),
                    ],
                  )
                ])));
  }

  void fetchDataList() {
    //  Map<String,dynamic> params ={"pageNum":mPage,"limit":20,"queryParam": keyword,"isProbe": selectedIndex == 0 ? "" : tabList1[selectedIndex]["value"]};
    HttpUtils().post(Api.getTestDriveList, data: queryParams).then((value) {
      hideLoading();
      if (value.resultCode == 200) {
        List list = value.data == null ? [] : value.data["records"];
        mCurrentStatus.onRefreshData(list, queryParams["pageNum"]);
        if (queryParams["pageNum"] == 1) {
          feedBackList.clear();
        }
        feedBackList.addAll(list);
      } else {
        mCurrentStatus?.onFail(value.errMsg);
      }
    }).catchError((e) {
      hideLoading();
    });
  }



  Widget ItemSingleInfoRow(content) {
    return Container(
      margin: EdgeInsets.only(top: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            content,
            style:  TextStyle(
                fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
          ),
        ],
      ),
    );
  }

  Widget ItemInfoRow(title, content) {
    return Container(
      margin: EdgeInsets.only(top: 5.px, left: 10.px),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          WText(
            title,
            style: TextStyle(
                fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
          ),
          SizedBox(
            width: 10.px,
          ),
          WText(
            content ?? "",
            style: TextStyle(
                fontSize: WDimens.tsMedium, color: WColors.mainTextColor),
          ),
        ],
      ),
    );
  }
}
